package logic

import (
	"context"
	"database/sql"
	"easychat/apps/social/socialmodels"
	"easychat/pkg/constants"
	"easychat/pkg/xerr"
	"github.com/pkg/errors"
	"time"

	"easychat/apps/social/rpc/internal/svc"
	"easychat/apps/social/rpc/social"

	"github.com/zeromicro/go-zero/core/logx"
)

var (
	ErrGroupReqBeforePass   = xerr.NewMsg("该申请已通过")
	ErrGroupReqBeforeRefuse = xerr.NewMsg("该申请已拒绝")
)

type GroupPutInHandleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGroupPutInHandleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GroupPutInHandleLogic {
	return &GroupPutInHandleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GroupPutInHandleLogic) GroupPutInHandle(in *social.GroupPutInHandleReq) (*social.GroupPutInHandleResp, error) {
	// todo: add your logic here and delete this line
	groupReq, err := l.svcCtx.GroupRequestsModel.FindOne(l.ctx, uint64(in.GroupReqId))
	if err != nil {
		return nil, errors.Wrapf(xerr.NewDBErr(), "【查询群申请失败】 err: %v", err)
	}

	switch constants.HandlerResult(groupReq.HandleResult.Int64) {
	case constants.PassHandlerResult: // 已通过
		return nil, errors.WithStack(ErrGroupReqBeforePass)
	case constants.RefuseHandlerResult: // 已拒绝
		return nil, errors.WithStack(ErrGroupReqBeforeRefuse)
	}

	groupReq.HandleResult = sql.NullInt64{
		Int64: int64(in.HandleResult),
		Valid: true,
	}

	if err = l.svcCtx.GroupRequestsModel.Update(l.ctx, groupReq); err != nil {
		return nil, errors.Wrapf(xerr.NewDBErr(), "【更新群申请失败】 err: %v", err)
	}

	if constants.HandlerResult(groupReq.HandleResult.Int64) != constants.PassHandlerResult {
		return &social.GroupPutInHandleResp{}, nil
	}

	member := &socialmodels.GroupMembers{
		Id:        0,
		GroupId:   groupReq.GroupId,
		UserId:    groupReq.ReqId,
		RoleLevel: int64(constants.AtLargeGroupRoleLevel),
		JoinTime: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
		OperatorUid: sql.NullString{
			String: in.HandleUid,
			Valid:  true,
		},
	}
	_, err = l.svcCtx.GroupMembersModel.Insert(l.ctx, nil, member)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewDBErr(), "【创建群成员失败】 err: %v, req: %v ", err, in)
	}
	return &social.GroupPutInHandleResp{
		GroupId: groupReq.GroupId,
	}, nil
}
